<template>
  <div id="app">
    <button @click="returnFn" class="btn btn-primary retrunBUtton">
      <i class="icon">⚡</i> 返回
    </button>
    <div class="container">
      <header>
        <h1>JSON格式化工具</h1>
        <p class="subtitle">在线格式化、验证和美化JSON数据</p>
      </header>

      <div class="main-content">
        <div class="input-section">
          <div class="section-title">
            <h2>输入JSON</h2>
            <div class="button-group">
              <button @click="formatJson" class="btn btn-primary">
                <i class="icon">⚡</i> 格式化
              </button>
              <button @click="clearInput" class="btn btn-secondary">
                <i class="icon">🗑️</i> 清空
              </button>
            </div>
          </div>
          <textarea
            v-model="inputJson"
            placeholder='在此处粘贴或输入JSON数据，例如：{"name": "John", "age": 30}'
            class="json-input"
            :class="{ error: hasError }"
          ></textarea>
          <div v-if="hasError" class="error-message"><i class="icon">❌</i> {{ errorMessage }}</div>
        </div>

        <div class="output-section">
          <div class="section-title">
            <h2>格式化结果</h2>
            <div class="button-group">
              <button @click="copyToClipboard" class="btn btn-primary" :disabled="hasError">
                <i class="icon">📋</i> {{ copyButtonText }}
              </button>
              <button @click="toggleTheme" class="btn btn-secondary">
                <i class="icon">{{ isDarkTheme ? '☀️' : '🌙' }}</i>
                {{ isDarkTheme ? '浅色' : '深色' }}
              </button>
            </div>
          </div>
          <pre
            class="json-output"
            :class="{ dark: isDarkTheme }"
          ><code ref="jsonOutput">{{ formattedJson }}</code></pre>
        </div>
      </div>

      <footer>
        <p>JSON格式化工具 v1.0 | 使用Vue 3开发</p>
      </footer>
    </div>
  </div>
</template>

<script>
export default {
  name: 'JsonFormatter',
  data () {
    return {
      inputJson: '',
      formattedJson: '',
      hasError: false,
      errorMessage: '',
      copyButtonText: '复制',
      isDarkTheme: false
    }
  },
  watch: {
    inputJson (newValue) {
      if (newValue.trim() === '') {
        this.formattedJson = ''
        this.hasError = false
        return
      }

      // 延迟格式化，避免频繁操作
      clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        this.formatJson()
      }, 500)
    }
  },
  methods: {
    returnFn () {
      this.$router.go(-1)
    },
    formatJson () {
      if (this.inputJson.trim() === '') {
        this.formattedJson = ''
        this.hasError = false
        return
      }

      try {
        // 尝试解析JSON
        const parsedJson = JSON.parse(this.inputJson)
        // 格式化JSON，使用2个空格缩进
        this.formattedJson = JSON.stringify(parsedJson, null, 2)
        this.hasError = false
      } catch (error) {
        this.hasError = true
        this.errorMessage = `JSON格式错误: ${error.message}`
        this.formattedJson = ''
      }
    },
    clearInput () {
      this.inputJson = ''
      this.formattedJson = ''
      this.hasError = false
      this.copyButtonText = '复制'
    },
    copyToClipboard () {
      if (this.hasError || !this.formattedJson) return

      navigator.clipboard.writeText(this.formattedJson).then(() => {
        this.copyButtonText = '已复制!'
        setTimeout(() => {
          this.copyButtonText = '复制'
        }, 2000)
      }).catch(err => {
        console.error('复制失败: ', err)
        this.copyButtonText = '复制失败'
        setTimeout(() => {
          this.copyButtonText = '复制'
        }, 2000)
      })
    },
    toggleTheme () {
      this.isDarkTheme = !this.isDarkTheme
    }
  },
  mounted () {
    // 设置示例JSON
    this.inputJson = '{"name": "JSON格式化工具", "version": "1.0", "features": ["格式化", "验证", "语法高亮"], "author": "Vue 3"}'
    this.formatJson()
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

#app {
  min-height: 100vh;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  position: relative;
}
.retrunBUtton {
  position: absolute;
  top: 100px;
  right: 100px;
}

.container {
  width: 100%;
  max-width: 1900px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

header {
  background: linear-gradient(to right, #4a00e0, #8e2de2);
  color: white;
  padding: 20px 30px;
  text-align: center;
}

h1 {
  font-size: 28px;
  margin-bottom: 5px;
}

.subtitle {
  font-size: 20px;
  opacity: 0.9;
}

.main-content {
  display: flex;
  flex-wrap: wrap;
  min-height: 700px;
}

.input-section,
.output-section {
  flex: 1;
  min-width: 300px;
  padding: 25px;
  display: flex;
  flex-direction: column;
}

.input-section {
  border-right: 1px solid #eaeaea;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-title h2 {
  font-size: 20px;
  color: #333;
}

.button-group {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 15px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(to right, #4a00e0, #8e2de2);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(74, 0, 224, 0.3);
}

.btn-primary:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  background: #f0f0f0;
  color: #333;
}

.btn-secondary:hover {
  background: #e0e0e0;
}

.json-input {
  flex: 1;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: 'Courier New', monospace;
  font-size: 20px;
  resize: none;
  outline: none;
  transition: border-color 0.3s;
}

.json-input:focus {
  border-color: #8e2de2;
}

.json-input.error {
  border-color: #e74c3c;
}

.error-message {
  margin-top: 10px;
  padding: 10px;
  background-color: #ffeaea;
  border-left: 4px solid #e74c3c;
  color: #c0392b;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.json-output {
  flex: 1;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
  overflow: auto;
  font-family: 'Courier New', monospace;
  font-size: 20px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.json-output.dark {
  background-color: #2d2d2d;
  color: #f8f8f2;
  border-color: #444;
}

footer {
  text-align: center;
  padding: 15px;
  background-color: #f5f5f5;
  color: #666;
  font-size: 14px;
}

.icon {
  font-style: normal;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .input-section {
    border-right: none;
    border-bottom: 1px solid #eaeaea;
  }

  .section-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .button-group {
    width: 100%;
    justify-content: flex-end;
  }
}

/* JSON语法高亮 */
.json-output code {
  display: block;
}

.json-output .string {
  color: #e74c3c;
}
.json-output .number {
  color: #9b59b6;
}
.json-output .boolean {
  color: #3498db;
}
.json-output .null {
  color: #7f8c8d;
}
.json-output .key {
  color: #2c3e50;
  font-weight: bold;
}

.json-output.dark .string {
  color: #f1c40f;
}
.json-output.dark .number {
  color: #9b59b6;
}
.json-output.dark .boolean {
  color: #3498db;
}
.json-output.dark .null {
  color: #95a5a6;
}
.json-output.dark .key {
  color: #ecf0f1;
  font-weight: bold;
}
</style>